<template>
  <el-dialog
    :title="dialogTitle"
    :visible.sync="dialogVisible"
    width="50%"
    @close="handleClose"
  >
    <el-form
      ref="userForm"
      :model="userForm"
      :rules="rules"
      label-width="100px"
    >
      <el-form-item label="用户名" prop="username">
        <el-input v-model="userForm.username" :disabled="isEdit" />
      </el-form-item>
      <el-form-item label="密码" prop="password" v-if="!isEdit">
        <el-input v-model="userForm.password" type="password" show-password />
      </el-form-item>
      <el-form-item label="姓名" prop="name">
        <el-input v-model="userForm.name" />
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input v-model="userForm.phone" />
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="userForm.email" />
      </el-form-item>
      <el-form-item label="性别">
        <el-radio-group v-model="userForm.gender">
          <el-radio :label="1">男</el-radio>
          <el-radio :label="2">女</el-radio>
          <el-radio :label="0">未知</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="部门">
        <el-select v-model="userForm.departmentId" placeholder="请选择部门">
          <el-option
            v-for="item in departmentOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="职位">
        <el-input v-model="userForm.position" />
      </el-form-item>
      <el-form-item label="状态">
        <el-switch
          v-model="userForm.status"
          :active-value="1"
          :inactive-value="0"
          active-text="启用"
          inactive-text="禁用"
        />
      </el-form-item>
      <el-form-item label="账号有效期">
        <el-date-picker
          v-model="userForm.expireTime"
          type="datetime"
          placeholder="选择日期时间"
        />
      </el-form-item>
      <el-form-item label="角色" prop="roleIds">
        <el-select
          v-model="userForm.roleIds"
          multiple
          placeholder="请选择角色"
        >
          <el-option
            v-for="item in roleOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="submitForm">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { addUser, updateUser, getUserRoleIds } from '@/api/user'
import { getDepartmentList } from '@/api/department'
import { getRoleList } from '@/api/role'

export default {
  name: 'UserForm',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    isEdit: {
      type: Boolean,
      default: false
    },
    userData: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      dialogVisible: false,
      userForm: {
        id: undefined,
        username: '',
        password: '',
        name: '',
        phone: '',
        email: '',
        gender: 0,
        departmentId: undefined,
        position: '',
        status: 1,
        expireTime: '',
        roleIds: []
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 4, max: 20, message: '长度在 4 到 20 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 8, max: 20, message: '长度在 8 到 20 个字符', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '请输入姓名', trigger: 'blur' }
        ],
        phone: [
          { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
        ],
        email: [
          { type: 'email', message: '邮箱格式不正确', trigger: 'blur' }
        ],
        roleIds: [
          { type: 'array', required: true, message: '请选择角色', trigger: 'change' }
        ]
      },
      departmentOptions: [],
      roleOptions: []
    }
  },
  computed: {
    dialogTitle() {
      return this.isEdit ? '编辑用户' : '添加用户'
    }
  },
  watch: {
    visible(val) {
      this.dialogVisible = val
      if (val) {
        this.fetchDepartments()
        this.fetchRoles()
        if (this.isEdit) {
          this.initEditForm()
        }
      }
    },
    dialogVisible(val) {
      this.$emit('update:visible', val)
    }
  },
  methods: {
    fetchDepartments() {
      getDepartmentList().then(response => {
        this.departmentOptions = response.data
      })
    },
    fetchRoles() {
      getRoleList().then(response => {
        this.roleOptions = response.data
      })
    },
    initEditForm() {
      // 复制用户数据到表单
      this.userForm = {
        id: this.userData.id,
        username: this.userData.username,
        name: this.userData.name,
        phone: this.userData.phone,
        email: this.userData.email,
        gender: this.userData.gender,
        departmentId: this.userData.departmentId,
        position: this.userData.position,
        status: this.userData.status,
        expireTime: this.userData.expireTime,
        roleIds: []
      }
      
      // 获取用户角色
      getUserRoleIds(this.userData.id).then(response => {
        this.userForm.roleIds = response.data
      })
    },
    handleClose() {
      this.resetForm()
    },
    resetForm() {
      this.userForm = {
        id: undefined,
        username: '',
        password: '',
        name: '',
        phone: '',
        email: '',
        gender: 0,
        departmentId: undefined,
        position: '',
        status: 1,
        expireTime: '',
        roleIds: []
      }
      this.$nextTick(() => {
        this.$refs.userForm && this.$refs.userForm.clearValidate()
      })
    },
    submitForm() {
      this.$refs.userForm.validate(valid => {
        if (valid) {
          if (this.isEdit) {
            updateUser(this.userForm).then(() => {
              this.$notify({
                title: '成功',
                message: '更新用户成功',
                type: 'success',
                duration: 2000
              })
              this.dialogVisible = false
              this.$emit('success')
            })
          } else {
            addUser(this.userForm).then(() => {
              this.$notify({
                title: '成功',
                message: '添加用户成功',
                type: 'success',
                duration: 2000
              })
              this.dialogVisible = false
              this.$emit('success')
            })
          }
        } else {
          return false
        }
      })
    }
  }
}
</script> 